class_name Player
extends Node2D

@export var stats: CharacterStats: set = _set_character_stats

@onready var sprite_2d: Sprite2D = %Sprite2D
@onready var stats_ui: StatsUI = %StatsUI
@onready var status_handler: StatusHandler = %StatusHandler
@onready var modifier_handler: ModifierHandler = %ModifierHandler


func _set_character_stats(value: CharacterStats) -> void:
	stats = value
	if not stats.stats_changed.is_connected(update_stats):
		stats.stats_changed.connect(update_stats)
	update_player()
	
func update_player() -> void:
	if not stats is CharacterStats:
		return
	if not is_inside_tree():
		await ready
	sprite_2d.texture = stats.art
	update_stats()
	
func update_stats() -> void:
	stats_ui.update_stats(stats)
	
func take_damage(value: int, which_modifier: Modifier.Type) -> void:
	if stats.health <= 0:
		return
	var modifier_value := modifier_handler.get_modified_value(value, which_modifier)
	sprite_2d.material = AutoLoader.WHITE_SPRITE_MATERIAL
	var tween := create_tween()
	tween.tween_callback(Shaker.shake.bind(self, 16, 0.15))
	tween.tween_callback(stats.take_damage.bind(modifier_value))
	tween.tween_interval(0.17)
	tween.finished.connect(func():
		sprite_2d.material = null
		if stats.health <= 0:
			Events.do_player_died()
			queue_free()
	)
